/* global window */
import mapboxgl from 'mapbox-gl';
import {instrumentGLContext} from '@luma.gl/gltools';
import {Buffer} from '@luma.gl/webgl';
import {Model} from '@luma.gl/engine';

// Create a Mapbox custom layer
// https://docs.mapbox.com/mapbox-gl-js/example/custom-style-layer/
class CustomLayer {
    constructor() {
      this.id = 'lumagl-layer';
      this.type = 'custom';
      this.renderingMode = '3d';
    }
  
    onAdd(m, gl) {
      instrumentGLContext(gl);
      this.map = m;
      this.gl = gl;
  
      const vertexSource = `
          attribute vec2 positions;
          attribute vec3 colors;
  
          uniform mat4 uPMatrix;
  
          varying vec3 vColor;
  
          void main() {
              vColor = colors;
              gl_Position = uPMatrix * vec4(positions, 0, 1.0);
          }
      `;
  
      const fragmentSource = `
          varying vec3 vColor;
  
          void main() {
              gl_FragColor = vec4(vColor, 0.8);
          }
      `;
  
      const positions = new Float32Array(8);

      const coordinates = [
        [100.98513, 20.758896], // Times Square
        [121.152, 23.909], // Rockafeller Center
        [110.9819, 30.7681], // Columbus Circle
        [118.86, 32.0484]
      ];
  
      coordinates.forEach((point, i) => {
        const coords = mapboxgl.MercatorCoordinate.fromLngLat(point);
        positions[i * 2] = coords.x;
        positions[i * 2 + 1] = coords.y;
      });
  
      this.positionBuffer = new Buffer(gl, new Float32Array(positions));
      this.colorBuffer = new Buffer(
        gl,
        new Float32Array([
            1.0, 0.0, 0.0,
            0.0, 1.0, 0.0,
            0.0, 0.0, 1.0,
            1.0, 1.0, 0.0
        ])
      );
  
      // Model to draw a triangle on the map
      this.model = new Model(gl, {
        id: 'my-program',
        vs: vertexSource,
        fs: fragmentSource,
        attributes: {
          positions: this.positionBuffer,
          colors: this.colorBuffer
        },
        drawMode: gl.TRIANGLE_STRIP,
        vertexCount: 4
      });
    }
  
    render(gl, matrix) {
      // Mapbox passes us a projection matrix
      this.model
        .setUniforms({
          uPMatrix: matrix
        })
        .draw();
    }
  
    onRemove() {
      // Cleanup
      this.positionBuffer.delete();
      this.colorBuffer.delete();
      this.model.delete();
    }

    clear(){
      // this.positionBuffer.delete();
      // this.colorBuffer.delete();
      this.model.delete();
      this.map.triggerRepaint();
    }
  }

  export default CustomLayer;
  